#include "Utilities.h"
#include "Snake.h"
#include "board.h"


Snake::Snake(Board * board) {
    this -> board = board;
}
void Snake::reset()
{
    for(int i=0; i <START_LENGTH; i++)
    {
        segments.push_back(Point(START_X - i, START_Y));
    }
    direction = GO_RIGHT;
    isDead = false;
}

void Snake::move() {
    int x, y;
    x = segments[0].x + movex[direction];
    y = segments[0].y + movey[direction];
    Point newSegment(x, y);
    segments.push_front(newSegment);
}

void Snake::update()
{
    if(isDead) {
        return;
    }
    if(checkForBorderCollision() | checkForSelfCollision()) 
    {
        isDead = true;
        return ;
    }

    if(checkForFoodCollision()) {
        board->food.relocate();
    } else {
        segments.pop_back();
    }
    move();
}

bool Snake::checkForBorderCollision()
{
    if(segments[0].x == 0 || segments[0].x == CELL_WIDTH - 1 || segments[0].y == 0 || segments[0].y == CELL_HEIGHT - 1) {
        return true;
    } else {
        return false;
    }
}

bool Snake::checkForSelfCollision()
{
    int headx = segments[0].x;
    int heady = segments[0].y;
    for (unsigned int i=1; i< segments.size(); i++) {
        if(headx == segments[i].x && heady == segments[i].y)
        {
            return true;
        }
    }
    return false;
}

bool Snake::checkForFoodCollision()
{
    int foodx = board->food.location.x;
    int foody = board->food.location.y;

    int headx = segments[0].x;
    int heady = segments[0].y;
    if(foodx == headx && foody == heady) {
        return true;
    } else {
        return false;
    }
}